﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QCYHApp
{
    public partial class FormMain : Form
    {
        InitFile init = new InitFile();
        MsSqlHelper mssql = new MsSqlHelper();
        AppUitls uitls = new AppUitls();
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();

        //private Thread proThreadForReport;
        //private Thread proThreadForRegistration;

        public FormMain()
        {
            InitializeComponent();
            init.ClearLog();
            //proThreadForReport = new Thread(AutoStart);
            //proThreadForRegistration = new Thread(AutoStart);

           // proThreadForReport.Start();
           // proThreadForRegistration.Start();

        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            DataColumn name = new DataColumn("name", Type.GetType("System.String"));
            DataColumn value = new DataColumn("value", Type.GetType("System.String"));
            dt.Columns.Add(name);
            dt.Columns.Add(value);
            DataRow dr1 = dt.NewRow();
            dr1["name"] = "检验报告";
            dr1["value"] = "SendPostBatch";
            dt.Rows.Add(dr1);
            DataRow dr = dt.NewRow();
            dr["name"] = "注册批件";
            dr["value"] = "SendPostDrug";
            dt.Rows.Add(dr);
            
            comboBox1.DataSource = dt;
            comboBox1.DisplayMember = "name";
            comboBox1.ValueMember = "value";
            //SdTP.Value = DateTime.Today.AddDays(-10);
            SdTP.Value = new System.DateTime(2021, 1, 1, 0, 0, 0, 0);
            EdTP.Value = DateTime.Today;

            if (InitFile.Auto.ToLower() == "true")
            {
                timer.Enabled = true;
                label10.Text = "双击勾选  自动传输已打开，请勿手动传输！";
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            progressBar1.Value = 0;
            string url = InitFile.url + "Uploader/uploaderDurg";
            string apiKey = InitFile.apiKey;
            string apiSecret = InitFile.apiSecret;
            string timeStamp = InitFile.GetTimeStamp();
            string sign = InitFile.md5(apiKey + apiSecret + timeStamp);
            txttimeStamp.Text = timeStamp;
            txtapiSecret.Text = apiSecret;
            txtsign.Text = sign;
            txtapiKey.Text = apiKey;
            txturl.Text = url;
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //点击"是(YES)"退出程序
            if (MessageBox.Show("确定要退出程序?", "安全提示",
                        System.Windows.Forms.MessageBoxButtons.YesNo,
                        System.Windows.Forms.MessageBoxIcon.Warning)
                == System.Windows.Forms.DialogResult.Yes)
            {
                this.Close();                  //关闭窗体
                this.Dispose();                //释放资源
                Application.Exit();            //关闭应用程序窗体
            }
        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = true;  //显示在系统任务栏
                this.WindowState = FormWindowState.Normal;  //还原窗体
            }
            this.WindowState = FormWindowState.Normal;
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //判断是否选择的是最小化按钮
            if (WindowState == FormWindowState.Minimized)
            {
                //隐藏任务栏区图标
                this.ShowInTaskbar = false;
                //图标显示在托盘区
                notifyIcon.Visible = true;
                this.WindowState = FormWindowState.Minimized;
            }
            else
            {
                this.WindowState = FormWindowState.Minimized;
            }
            e.Cancel = true;
        }

        private void FormMain_SizeChanged(object sender, EventArgs e)
        {
            //判断是否选择的是最小化按钮
            if (WindowState == FormWindowState.Minimized)
            {
                //隐藏任务栏区图标
                this.ShowInTaskbar = false;
                //图标显示在托盘区
                notifyIcon.Visible = true;
                notifyIcon.ShowBalloonTip(3, "系统信息", "【数据传输】已启动", ToolTipIcon.Info);
            }
            else
            {
                this.ShowInTaskbar = true;//任务栏
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            //点击"是(YES)"退出程序
            if (MessageBox.Show("确定要退出程序?", "安全提示",
                        System.Windows.Forms.MessageBoxButtons.YesNo,
                        System.Windows.Forms.MessageBoxIcon.Warning)
                == System.Windows.Forms.DialogResult.Yes)
            {
                this.Close();                  //关闭窗体
                this.Dispose();                //释放资源
                Application.Exit();            //关闭应用程序窗体
            }
        }

        public int number = 0;

        private void btnStart_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedTab = tabControl1.TabPages[1];
            string StartDate = SdTP.Value.ToString("yyy-MM-dd");
            string EndDate = EdTP.Value.ToString("yyy-MM-dd");
            string BatchNo = comboBox2.Text;
            btnStart.Enabled = false;
            btnSelStart.Enabled = false;

            btnCancel.Enabled = true;
            comboBox1.Enabled = false;
            comboBox2.Enabled = false;
            label5.Text = "处理进度：0/0条";
            label6.Text = "0%";
            progressBar1.Value = 0;

            string SycName = comboBox1.SelectedValue.ToString();
            string SycText = comboBox1.Text.ToString();
            string title = string.IsNullOrEmpty(BatchNo) ? SycText + "-" + InitFile.title : BatchNo + "-" + SycText + "-" + InitFile.title;
            this.Text = title;
            notifyIcon.Tag = title;
            notifyIcon.Text = title;
            //notifyIcon.ShowBalloonTip(3, "系统信息", "【" + title + "】已启动", ToolTipIcon.Info);
            uitls.SyncStr(SycName, BatchNo, StartDate, EndDate);
            uitls.result = "";
            number = uitls.number;
            progressBar1.Maximum = number;
            resultTextBox.Text = "任务开始..." + "\r\n";
            backgroundWorker1.RunWorkerAsync(SycName);             
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string syncname = e.Argument.ToString();
            uitls.HotSync(backgroundWorker1, e);
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            label5.Text = "处理进度:" + Convert.ToString(e.ProgressPercentage) + "/" + number + "条";
            label6.Text = (e.ProgressPercentage * 100 / number).ToString() + "%";
            resultTextBox.Text += uitls.result;
            resultTextBox.SelectionStart = resultTextBox.Text.Length;
            resultTextBox.ScrollToCaret();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
                if (e.Cancelled)
                {
                    resultTextBox.Text += "任务取消。" + "\r\n";
                }
                else if (e.Error != null)
                {
                    resultTextBox.Text += "出现异常: " + e.Error + "\r\n";
                }
                else
                {
                    resultTextBox.Text += "任务完成。 " + "\r\n";
                    btnStart.Enabled = true;
                    btnSelStart.Enabled = true;
                    btnCancel.Enabled = false;
                    comboBox1.Enabled = true;
                    comboBox2.Enabled = true;
                }
                resultTextBox.SelectionStart = resultTextBox.Text.Length;
                resultTextBox.ScrollToCaret();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            btnStart.Enabled = true;
            btnSelStart.Enabled = true;
            btnCancel.Enabled = false;
            comboBox1.Enabled = true;
            comboBox2.Enabled = true;
            backgroundWorker1.CancelAsync();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            string StartDate = SdTP.Value.ToString("yyy-MM-dd");
            string EndDate = EdTP.Value.ToString("yyy-MM-dd");
            string BatchNo = comboBox2.Text;
            label6.Text = "0%";

            tabControl1.SelectedTab = tabControl1.TabPages[0];
            string SycName = comboBox1.SelectedValue.ToString();
            string SycText = comboBox1.Text.ToString();
            string title = string.IsNullOrEmpty(BatchNo) ? SycText + "-" + InitFile.title : BatchNo + "-" + SycText + "-" + InitFile.title;
            this.Text = title;
            notifyIcon.Tag = title;
            notifyIcon.Text = title;
            //notifyIcon.ShowBalloonTip(3, "系统信息", "【" + title + "】已启动", ToolTipIcon.Info);
            uitls.SyncStr(SycName, BatchNo, StartDate, EndDate);
            uitls.result = "";
            number = uitls.number;
            progressBar1.Maximum = number;
            dGV.DataSource = uitls.dataTable;

            dGV.Columns["imageid"].Visible = false;
            dGV.Columns["spbh"].HeaderText = "商品编号";
            dGV.Columns["spmch"].HeaderText = "商品名称";
            dGV.Columns["shpgg"].HeaderText = "规格";
            dGV.Columns["dw"].HeaderText = "单位";
            dGV.Columns["shengccj"].HeaderText = "生产厂家";            
            dGV.Columns["detailid"].Visible = false;

            if (SycName == "SendPostDrug") { dGV.Columns["qualification_type_id"].Visible = false; }
            if (SycName == "SendPostBatch")
            {
                dGV.Columns["batchid"].HeaderText = "批号";
                dGV.Columns["drugBatchid"].Visible = false;
            }
            dGV.Columns["url"].HeaderText = "图片地址";
            dGV.Columns["url"].DisplayIndex = uitls.dataTable.Columns.Count;


            label5.Text = "处理进度:0/" + number + "条";
            
        }

        private void btnSelStart_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedTab = tabControl1.TabPages[1];
            btnStart.Enabled = false;
            btnSelStart.Enabled = false;
            btnCancel.Enabled = true;
            comboBox1.Enabled = false;
            comboBox2.Enabled = false;
            label5.Text = "处理进度：0/0条";
            label6.Text = "0%";
            progressBar1.Value = 0;
            string title =  InitFile.title;
            this.Text = title;
            notifyIcon.Tag = title;
            notifyIcon.Text = title;

            DataTable Updt = new DataTable();
            Updt.Clear();

            foreach (DataGridViewColumn headerCell in dGV.Columns)
            {
                Updt.Columns.Add(headerCell.Name);            
            }

            foreach (DataGridViewRow item in dGV.Rows)
            {
                DataGridViewCheckBoxCell dataGridViewCheckBoxCell = (DataGridViewCheckBoxCell)item.Cells[0];
                if ((bool)dataGridViewCheckBoxCell.FormattedValue)
                {
                    DataRow dr = Updt.NewRow();
                    for (int i = 0; i < Updt.Columns.Count; i++)
                    {
                        dr[i] = item.Cells[i].Value.ToString();
                    }
                    Updt.Rows.Add(dr);
                }  
            }
            string SycName = comboBox1.SelectedValue.ToString();
            string SycText = comboBox1.Text.ToString();
            uitls.SyncStr(Updt);
            uitls.result = "";
            number = uitls.number;
            progressBar1.Maximum = number;
            resultTextBox.Text = "任务开始..." + "\r\n";
            backgroundWorker1.RunWorkerAsync(SycName); 
        }

        private void dGV_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                if (Convert.ToBoolean((dGV.Rows[e.RowIndex].Cells[0] as DataGridViewCheckBoxCell).Value))
                {
                    (dGV.Rows[e.RowIndex].Cells[0] as DataGridViewCheckBoxCell).Value = false;
                    //dGV.Rows[e.RowIndex].Cells[0].Style.BackColor = Color.White;
                    dGV.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
                    
                }
                else
                {
                    (dGV.Rows[e.RowIndex].Cells[0] as DataGridViewCheckBoxCell).Value = true;
                    //dGV.Rows[e.RowIndex].Cells[0].Style.BackColor = SystemColors.ActiveCaption;
                    dGV.Rows[e.RowIndex].DefaultCellStyle.BackColor = SystemColors.ActiveCaption;
                    //dGV.Rows[e.RowIndex].Cells[0].Style.BackColor = Color.Red;
                }
            }           
        }

        private void dGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                DataGridViewColumn column = dGV.Columns[e.ColumnIndex];
                if (column is DataGridViewButtonColumn)
                {
                    string url = dGV.Rows[e.RowIndex].Cells["url"].Value.ToString();
                    System.Diagnostics.Process.Start(url);
                    //MessageBox.Show(url);
                    //这里可以编写你需要的任意关于按钮事件的操作~
                    //MessageBox.Show("按钮被点击");
                    //this.dataGridView1.CurrentRow.Visible=false;//隐藏当前行
                    //this.dGV.Rows.RemoveAt(e.RowIndex);//删除当前行
                }
            }
        }

        private void AutoStart()
        {
            btnStart.Enabled = false;
            btnSelStart.Enabled = false;
            btnCancel.Enabled = true;
            comboBox1.Enabled = false;
            comboBox2.Enabled = false;
            label5.Text = "处理进度：0/0条";
            label6.Text = "0%";
            progressBar1.Value = 0;
            string title = InitFile.title;
            this.Text = title;
            notifyIcon.Tag = title;
            notifyIcon.Text = title;

            DataTable Updt = new DataTable();
            Updt.Clear();

            foreach (DataGridViewColumn headerCell in dGV.Columns)
            {
                Updt.Columns.Add(headerCell.Name);
            }

            foreach (DataGridViewRow item in dGV.Rows)
            {
                DataGridViewCheckBoxCell dataGridViewCheckBoxCell = (DataGridViewCheckBoxCell)item.Cells[0];
                if ((bool)dataGridViewCheckBoxCell.FormattedValue)
                {
                    DataRow dr = Updt.NewRow();
                    for (int i = 0; i < Updt.Columns.Count; i++)
                    {
                        dr[i] = item.Cells[i].Value.ToString();
                    }
                    Updt.Rows.Add(dr);
                }
            }
            string SycName = "SendPostDrug";
            uitls.SyncStr(Updt);
            uitls.result = "";
            number = uitls.number;
            progressBar1.Maximum = number;
            resultTextBox.Text = "任务开始..." + "\r\n";
            backgroundWorker1.RunWorkerAsync(SycName); 
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            tabControl1.SelectedTab = tabControl1.TabPages[1];
            string StartDate = DateTime.Now.AddDays(-1).ToString("yyy-MM-dd");
            string EndDate = DateTime.Now.AddDays(1).ToString("yyy-MM-dd");
            string BatchNo = "";
            btnStart.Enabled = false;
            btnSelStart.Enabled = false;

            btnCancel.Enabled = true;
            comboBox1.Enabled = false;
            comboBox2.Enabled = false;
            label5.Text = "处理进度：0/0条";
            label6.Text = "0%";
            progressBar1.Value = 0;

            string SycName = "SendPostDrug";
            string SycText = "注册批件";
            string title = string.IsNullOrEmpty(BatchNo) ? SycText + "-" + InitFile.title : BatchNo + "-" + SycText + "-" + InitFile.title;
            this.Text = title;
            notifyIcon.Tag = title;
            notifyIcon.Text = title;
            //notifyIcon.ShowBalloonTip(3, "系统信息", "【" + title + "】已启动", ToolTipIcon.Info);
            uitls.SyncStr(SycName, BatchNo, StartDate, EndDate);
            uitls.result = "";
            number = uitls.number;
            progressBar1.Maximum = number;
            resultTextBox.Text = "任务开始..." + "\r\n";
            backgroundWorker1.RunWorkerAsync(SycName);  
        }

    }
}
